package cn.ee.dfs.wx;

import cn.ee.dfs.common.entity.DfsResponse;
import cn.ee.dfs.common.utils.BeanUtil;
import cn.ee.dfs.common.utils.NetTool;
import cn.ee.dfs.common.utils.RedisTool;
import cn.ee.dfs.wx.model.WxUser;
import cn.ee.dfs.wx.service.IWxuserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 作者: tianwenju
 * @version 1.0
 * @project 金税三期工程核心征管及应用总集成项目
 * @package cn.ee.dfs.wx
 * @file PhoneNumberController.java 创建时间:2023年07月26日 11:22
 * @title 标题（要求能简洁地表达出类的功能和职责）
 * @description 描述（简要描述类的职责、实现方式、使用注意事项等）
 * @copyright Copyright (c) 2020 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 * @module 模块: 模块名称
 * @reviewer 审核人:
 * @history 修订历史（历次修订内容、修订人、修订时间等）
 */
@RequestMapping("/wx/api")
@RestController
public class PhoneNumberController {


    @Autowired
    private RedisTool redisTool;

    @Autowired
    private IWxuserService wxuserService;

    /**
     * @param data
     * @return
     */
    @PostMapping("/getPhoneNumber")
    public Object getPhoneNumber(@RequestBody JSONObject data) {
        String accessToken = getAccessToken();
        System.out.println("---getPhoneNumber--accessToken =>" + accessToken);


        //通过accessToken和code来获取用户手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;


        //封装请求体
        Map<String, String> paramMap = new HashMap<>();
        //每个code只能使用一次，code的有效期为5min
        paramMap.put("code", data.get("code").toString());

        //封装请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
//        //通过RestTemplate发送请求，获取到用户手机号码
//        RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

        String result = NetTool.post(url, paramMap);
//{
//    "errcode":0,
//    "errmsg":"ok",
//    "phone_info": {
//        "phoneNumber":"xxxxxx",
//        "purePhoneNumber": "xxxxxx",
//        "countryCode": 86,
//        "watermark": {
//            "timestamp": 1637744274,
//            "appid": "xxxx"
//        }
//    }
//}
        JSONObject resultData = JSON.parseObject(result);
        System.out.println("--后端--getPhoneNumber--response =>" + result);
        String phoneNumber;
        String purePhoneNumber;

        JSONObject phoneInfo = resultData.getJSONObject("phone_info");
        if (!Objects.isNull(phoneInfo)) {
            phoneNumber = phoneInfo.getString("phoneNumber");
            purePhoneNumber = phoneInfo.getString("purePhoneNumber");
        }

        phoneNumber = "86+13186137213";
        purePhoneNumber = "13186137213";
        // TODO: 2023/7/28 保存 数据库 手机号码
        WxUser userInfo = data.toJavaObject(WxUser.class);
        userInfo.setPhone(phoneNumber);
        userInfo.setPurePhone(purePhoneNumber);
        WxUser user = wxuserService.getOne(Wrappers.lambdaQuery(new WxUser(userInfo.getOpenId())).last("LIMIT 1"));
        System.out.println("数据库 查询user = " + user);


        if (Objects.isNull(user)) {
            userInfo.setCreateTime(new Date());
            userInfo.setStatus(WxUser.STATUS_VALID);
            wxuserService.saveOrUpdate(userInfo);
        } else {
            userInfo.setModifyTime(new Date());
            System.out.println("---before copy->user = " + user);

            BeanUtil.copyProperties(userInfo, user);
            System.out.println("---after copy->user = " + user);
            wxuserService.saveOrUpdate(user);
        }

        //返回到前端展示
        return new DfsResponse().success().data(userInfo);
    }

    /**
     * 通过appid和secret来获取token
     *
     * @return access_token
     */
    private String getAccessToken() {
        // {"access_token":"ACCESS_TOKEN","expires_in":7200}
        String access_token = (String) redisTool.get("access_token");
        if (StringUtils.isEmpty(access_token)) {
            String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WXContent.APPID, WXContent.APP_SECRET);
            JSONObject token = JSON.parseObject(NetTool.get(tokenUrl));
            access_token = token.getString("access_token");
            int expires = token.getIntValue("expires_in");
            redisTool.set("access_token", access_token, expires);
        }
        return access_token;
    }
}